package com.zyy.study.redisson.config;

import org.redisson.Redisson;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {
    @Value("${spring.redis.host}")
    String host;
    @Value("${spring.redis.port}")
    String port;

    @Value("${redis.semaphore.key}")
    String key;

    @Value("${redis.semaphore.permits}")
    int permits;
    @Bean
    public Config getConfig() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + host + ":" + port);
        return config;
    }

    @Bean
    public RedissonClient redissonClient(@Qualifier("getConfig") Config config) {
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }
    @Bean
    public RSemaphore getSemaphore(@Qualifier("redissonClient") RedissonClient redissonClient){
        RSemaphore semaphore = redissonClient.getSemaphore(key);
        semaphore.trySetPermits(permits);
        return semaphore;
    }

}
